<template>
  <a-spin :loading="loading">
    <div class="folder-wrapper">
      <div class="folder-header">
        <a-space :size="16">
          <a-input v-model="searchValue" placeholder="文件夹名" allow-clear />
          <a-button type="primary" shape="circle" @click="handleAdd()">
            <icon-plus />
          </a-button>
        </a-space>
      </div>

      <a-tree
        key="id"
        v-model:selected-keys="selectedKeys"
        :data="folderTreeData"
        :field-names="fieldNames"
        :block-node="true"
        size="large"
        @select="handleSelect">
        <template #extra="nodeData">
          <a-dropdown v-if="nodeData.id !== 0" trigger="hover">
            <IconMore
              style="position: absolute; top: 10px; right: 8px; font-size: 12px;"
            />
            <template #content>
              <a-doption @click="handleAdd(nodeData.id)">新建文件夹</a-doption>
              <a-doption @click="handleEdit(nodeData)">重命名</a-doption>
              <a-doption @click="handleDelete(nodeData)">删除</a-doption>
            </template>
          </a-dropdown>
        </template>

      </a-tree>

      <!--  添加 编辑  -->
      <a-modal
        v-model:visible="dialogVisible"
        title="创建文件夹"
        width="420px"
        :footer="false"
      >
        <a-form
          ref="formRef"
          :model="formState"
          auto-label-width
          @submit="handleSubmit"
        >
          <a-form-item label="上级分类" field="parent_id">
            <a-tree-select
              v-model="formState.parent_id"
              node-key="id"
              :data="folderTreeData"
              :field-names="fieldNames"
              placeholder="请选择上级目录"
              allow-clear
            />
          </a-form-item>

          <a-form-item
            label="文件夹名"
            field="name"
            :rules="[{ required: true, min: 2, max: 10, message: '分组名2~10个字符', trigger: 'change' }]">
            <a-input v-model="formState.name" placeholder="请输入文件夹名"></a-input>
          </a-form-item>
          <div class="form-footer mt-24">
            <a-button key="submit" html-type="submit" type="primary" :loading="loading">确 定</a-button>
            <a-button class="ml-24" @click="handleCancel">取 消</a-button>
          </div>
        </a-form>
      </a-modal>
    </div>
  </a-spin>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch, defineEmits } from "vue";
import { Message } from "@arco-design/web-vue";
import { IconMore } from "@arco-design/web-vue/es/icon";
import get from "lodash/get";
import { getFolderTree, folderCreate, folderUpdate, folderDelete } from "@/api/content/drive.ts";
import useLoading from "@/hooks/loading.ts";

interface EmitEvent {
  (e: "update:modelValue", params: string): void;
}

const emits = defineEmits<EmitEvent>();// 双向绑定 数据

const props = defineProps({
  modelValue: String
});

const fieldNames = {
  key: "id",
  title: "name",
  children: "children"
};

const searchValue = ref("");
const selectedKeys = ref([]);

watch(
  () => props.modelValue,
  (val) => {
    if (val && val.length) {
      // 将值转为数组
      selectedKeys.value = [props.modelValue];
    } else {
      selectedKeys.value = [];
    }
  },
  { deep: true, immediate: true }
);

const handleSelect = (newSelectedKeys, event) => {
  console.log("select: ", selectedKeys.value, newSelectedKeys, event);
  const activeKey = newSelectedKeys[0];
  selectedKeys.value = newSelectedKeys
  // 只更新folder_id
  emits("update:modelValue", JSON.parse(JSON.stringify(activeKey)));
};

const { loading, setLoading } = useLoading(true);
const folderTreeData = ref([]);

async function fetchTableData() {
  setLoading(true);
  try {
    const { data } = await getFolderTree();
    folderTreeData.value = [{ name: "全部文件", id: 0 }].concat(get(data, "list", []) || []);
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchTableData();
});

// 创建编辑弹窗
const dialogVisible = ref(false);
const formRef = ref();
const formState = reactive({
  id: "",
  parent_id: 0,
  name: ""
});


// 添加
function handleAdd(parentId) {
  if (parentId) {
    formState.parent_id = parentId;
  }
  dialogVisible.value = true;
}

// 重命名
function handleEdit(record) {
  if (record.id) {
    dialogVisible.value = true;
    formState.id = record.id;
    formState.parent_id = record.parent_id;
    formState.name = record.name;
  }
}

async function handleDelete(record) {
  if (!record.id) return;
  setLoading(true);
  try {
    // const params = {
    //   ...formState
    // };

    await folderDelete(record);

    Message.success("删除成功");
    fetchTableData();
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

// 取消
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  dialogVisible.value = false;
};

const handleSubmit = async ({ values, errors }) => {
  console.log("values:", values, "\nerrors:", errors);
  if (!errors) {
    try {
      const params = {
        ...formState
      };

      let result = {};
      if (params.id) {
        result = await folderUpdate(params);
      } else {
        result = await folderCreate(params);
      }

      const { msg } = result;

      Message.success(msg || "更新成功！");
      handleCancel();
      fetchTableData();
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  }
};
</script>

<style scoped lang="less">
.folder-wrapper {
  padding: 16px;

  .folder-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
}

.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
